<template>
  <div class="app-container">
    <div class="filter-container" v-show="filterIsShow">
      {{ $t('任务名称') }}
      <el-input size="small" clearable filterable style="width: 200px;" v-model="searchKey.name"
                :placeholder="$t('请输入任务名称')"></el-input>
      {{ $t('任务状态') }}
      <el-select size="small" clearable filterable v-model="searchKey.status" clearable
                 :placeholder="$t('请选择任务状态')">
        <el-option v-for="item in taskStatus" :value="item.value" :label="item.label"><i :class="item.icon">
          {{ item.label }}</i></el-option>
      </el-select>
      <el-button size="mini" icon="el-icon-search" @click="getJobs" type="primary">{{ $t('搜索') }}</el-button>
      <el-button size="mini" icon="el-icon-refresh" @click="handleReset(searchKey)">{{ $t('重置') }}</el-button>
    </div>
    <el-row :style="{'margin-top': '5px'}">
      <!--      <el-button icon="el-icon-plus" size="mini" type="primary" plain>{{ $t('新增') }}</el-button>-->
      <el-button :disabled="editDisabled" icon="el-icon-edit" @click="handlerSelectionChangeEdit" size="mini"
                 type="success" plain>{{ $t('修改') }}
      </el-button>
      <!--      <el-button :disabled="deleteDisabled" @click="handlerSelectionChangeDeleted()" icon="el-icon-delete" size="mini" type="danger" plain>{{ $t('删除') }}</el-button>-->
      <el-button @click="handleLog" icon="el-icon-s-operation" size="mini" type="warning" plain>{{ $t('日志') }}</el-button>

      <el-tooltip class="item" effect="dark" :content="$t('刷新表单')" placement="top">
        <el-button @click="getJobs" size="mini" :style="{'float':'right'}" icon="el-icon-refresh" circle></el-button>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" :content="$t('隐藏搜索')" placement="top">
        <el-button @click="filterIsShow=!filterIsShow" size="mini" :style="{'float':'right'}" icon="el-icon-search"
                   circle></el-button>
      </el-tooltip>
    </el-row>
    <!--    数据表格-->
    <el-table
      :header-cell-style="{background:'#eef1f6',color:'#606266',top:'5px'}"
      :row-class-name="tableRowClassName"
      ref="multipleTable"
      :data="scheduledJobList"
      tooltip-effect="dark"
      style="width: 100%;"
      v-loading="listLoading"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column align="center" label="任务编号" width="120">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="name" label="任务名称" width="200">
      </el-table-column>
      <el-table-column align="center" prop="className" label="调用目标" width="250" show-overflow-tooltip>
      </el-table-column>
      <el-table-column align="center" prop="cron" ailgn="center" label="cron执行表达式" show-overflow-tooltip>
      </el-table-column>
      <el-table-column align="center" prop="type" label="执行策略" width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-tag effect="dark" size="small" type="success"> {{ taskTypeMap[scope.row.type] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="operateUser" label="操作人" width="150" show-overflow-tooltip>
      </el-table-column>
      <el-table-column align="center" prop="status" label="状态" width="150">
        <template slot-scope="scope">
          <el-switch
            active-color="#13ce66"
            inactive-color="#ff4949"
            v-show="scope.row.isDie"
            v-model="scope.row.status"
            @change="switchValue(scope.row)">
          </el-switch>
          <i v-show="!scope.row.isDie" :style="{color: 'red'}" class="el-icon-remove-outline">{{ $t('已终止') }}</i>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="desc" label="任务描述" width="250" show-overflow-tooltip>
      </el-table-column>
      <el-table-column align="center" :label="$t('Operate')" class-name="small-padding fixed-width" width="200">
        <template slot="header" slot-scope="{row}">
          {{ $t('Operate') }}
          <i class="el-icon-setting" style="color: #d35e32;"></i>
        </template>
        <template slot-scope="scope">
          <el-row>
            <el-button @click="handlerEdit(scope.row)" type="text"><i class="el-icon-edit">{{$t('修改')}}</i>
            </el-button>
            <!--            <el-popconfirm
                          :confirm-button-text="$t('好的')"
                          :cancel-button-text="$t('不用了')"
                          @confirm="handlerDeleted(scope.row)"
                          icon="el-icon-info"
                          icon-color="red"
                          :title="$t('确定删除吗？')">
                          <el-button slot="reference" type="text"><i class="el-icon-delete"></i>{{ $t('删除') }}</el-button>
                        </el-popconfirm>-->

            <el-dropdown size="small" @command="handleDropdownClick">
              <span class="el-dropdown-link">
               <el-button type="text">{{$t('更多')}}<i class="el-icon-d-arrow-right"></i></el-button>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-show="scope.row.status==1" :command="{item:scope.row,type:1}" icon="el-icon-caret-right">{{
                    $t('执行一次')
                  }}
                </el-dropdown-item>
                <el-dropdown-item :command="{item:scope.row,type:2}" icon="el-icon-view">{{
                    $t('任务详情')
                  }}
                </el-dropdown-item>
                <el-dropdown-item :command="{item:scope.row,type:3}" icon="el-icon-s-operation">{{
                    $t('调度日志')
                  }}
                </el-dropdown-item>
                <el-popconfirm
                  @confirm="handleTaskDieClick(scope.row)"
                  :confirm-button-text="$t('好的')"
                  :cancel-button-text="$t('不用了')"
                  icon="el-icon-info"
                  icon-color="red"
                  :title="$t('任务一旦终止不可撤回！确定终止吗？')">
                  <el-dropdown-item slot="reference" :command="{item:scope.row,type:4}" icon="el-icon-remove-outline">
                    {{ $t('终止任务') }}
                  </el-dropdown-item>
                </el-popconfirm>

              </el-dropdown-menu>
            </el-dropdown>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>10" :total="searchKey.total" :page.sync="searchKey.page" :limit.sync="searchKey.limit"
                @pagination="getJobs"/>

    <!--    修改任务-->
    <el-dialog width="40%" title="修改任务" :visible.sync="dialogTaskVisible">
      <el-form :model="taskForm" :rules="taskRules" ref="taskForm" label-width="100px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="taskForm.name"></el-input>
        </el-form-item>
        <el-form-item label="调用目标" prop="className">
          <el-input disabled v-model="taskForm.className"></el-input>
        </el-form-item>
        <el-form-item label="cron表达式" prop="cron">
          <el-input placeholder="请输入内容" v-model="taskForm.cron">
            <el-button @click="dialogCronVisible=true" slot="append">{{ $t('生成表达式') }} <i class="el-icon-time"></i>
            </el-button>
          </el-input>
        </el-form-item>
<!--        <el-form-item label="执行策略" prop="type">
          <el-radio-group v-model="taskForm.type" size="small">
            <el-radio-button :label="1">{{ $t('立即执行') }}</el-radio-button>
            <el-radio-button :label="2">{{ $t('执行一次') }}</el-radio-button>
            <el-radio-button :label="3">{{ $t('放弃执行') }}</el-radio-button>
          </el-radio-group>
        </el-form-item>-->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="taskForm.status" size="small">
            <el-radio :label="true" name="status">{{ $t('开启') }}</el-radio>
            <el-radio :label="false" name="status">{{ $t('暂停') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="任务描述" prop="desc">
          <el-input type="textarea" :autosize="{ minRows: 4}" placeholder="请输入内容"
                    v-model="taskForm.desc"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button icon="el-icon-edit" type="primary" @click="submitTaskEditForm('taskForm')">{{$t('提交编辑')}}</el-button>
<!--          <el-button @click="resetForm('taskForm')">重置</el-button>-->
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="dialogCronVisible"
      width="30%">
      <vcrontab @hide="(showCron = true)" @fill="crontabFill" :expression="expression" ref="cron"></vcrontab>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogDetailsVisible"
      width="40%">
      <el-descriptions border class="margin-top" title="任务详情"  direction="vertical">
        <el-descriptions-item label="任务编号" :span="2">{{ this.taskForm.id }}</el-descriptions-item>
        <el-descriptions-item label="任务名称" :span="2">{{ this.taskForm.name }}</el-descriptions-item>
        <el-descriptions-item label="调用目标" :span="2">{{ this.taskForm.className }}</el-descriptions-item>
        <el-descriptions-item label="cron" :span="2">{{ this.taskForm.cron }}</el-descriptions-item>
        <el-descriptions-item label="操作人" :span="2">{{ this.taskForm.operateUser }}</el-descriptions-item>
        <el-descriptions-item label="状态" :span="2">{{ this.taskForm.status ? $t('开启') : $t('暂停') }}
        </el-descriptions-item>
        <el-descriptions-item label="执行策略" :span="2">{{ taskTypeMap[this.taskForm.type] }}</el-descriptions-item>
        <el-descriptions-item label="任务描述" :span="3">{{ this.taskForm.desc }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>


  </div>
</template>

<script>
import {
  scheduledJobs,
  openOrclose,
  deleted,
  abortMission,
  batchDeleted,
  triggerJob,
  rescheduleJob
} from "@/api/scheduled";
import Pagination from '@/components/Pagination'
import vcrontab from "vcrontab";

export default {
  name: "scheduled",
  components: {Pagination, vcrontab},
  data() {
    const taskTypeMap = {
      1: this.$t('立即执行'),
      2: this.$t('执行一次'),
      3: this.$t('放弃执行')
    }
    return {
      dialogCronVisible: false,
      dialogDetailsVisible: false,
      showCron: false,
      expression: "",
      filterIsShow: true,
      dialogTaskVisible: false,
      listLoading: false,
      scheduledJobList: [],
      taskForm: {
        name: undefined,
        className: undefined,
        cron: undefined,
        type: undefined,
        status: undefined,
        operateUser: undefined,
        desc: ''
      },
      total: 0,
      deleteDisabled: true,
      editDisabled: true,
      multipleSelection: [],
      taskTypeMap,
      searchKey: {
        name: undefined,
        status: undefined,
        type: undefined,
        page: 1,
        limit: 20,
      },
      taskStatus: [{
        value: '1',
        label: '开启',
        icon: 'el-icon-timer'
      }, {
        value: '0',
        label: '暂停',
        icon: 'el-icon-video-play'
      }, {
        value: '3',
        label: '终止',
        icon: 'el-icon-remove-outline'
      }],
      taskRules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3,  message: '长度在 3 到 N 个字符', trigger: 'blur' }
        ],
        className: [
          { required: true, message: '请输入调度目标名称', trigger: 'blur' }
        ],
        cron: [
          { required: true, message: '请输入CRON名称', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择执行状态', trigger: 'change' }
        ],
        desc: [
          { required: true, message: '请输入任务描述', trigger: 'blur' },
          { min: 3,  message: '长度在 3 到 N 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  updated() {
    try {
      // 历史时间
      this.$refs.cron.$el.childNodes[1].childNodes[1].hidden = true
      // 取消按钮
      this.$refs.cron.$el.childNodes[1].childNodes[2].childNodes[2].style.display = 'none';
      // console.log(this.$refs.cron);
    } catch (e) {
    }

  },
  created() {
    this.getJobs()
  },
  methods: {
    handleReset(searchKey) {
      searchKey.name = ''
      searchKey.status = ''
    },
    getJobs() {
      this.listLoading = true
      scheduledJobs(this.searchKey).then(res => {
        this.listLoading = false
        this.scheduledJobList = res.data.data.list
        this.total = res.data.data.total
      }).catch(() => {
        this.scheduledJobList = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length > 0) {
        this.deleteDisabled = false
      } else {
        this.deleteDisabled = true
      }
      if (this.multipleSelection.length == 1) {
        this.editDisabled = false
      } else {
        this.editDisabled = true
      }
      console.log(JSON.stringify(this.multipleSelection))
    },
    tableRowClassName({row, rowIndex}) {
      if (row.isDie) {
        return 'warning-row';
      }
      return '';
    },
    switchValue(row) {
      openOrclose({id: row.id}).then(res => {
        this.$notify({
          title: '成功',
          message: '执行成功',
          type: 'success'
        });
      }).catch(() => {
        row.status=false
        this.$notify.error({
          title: '失败',
          message: '执行失败'
        });
      })
    },
    handlerDeleted(row) {
      deleted({id: row.id}).then(res => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success'
        });
      }).catch(() => {
        this.$notify.error({
          title: '失败',
          message: '删除失败'
        });
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.taskForm = {}
    },
    submitTaskEditForm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          rescheduleJob(this.taskForm).then(res => {
            this.$notify({
              title: '成功',
              message: '更新成功，编辑请继续，结束请关闭页面',
              type: 'success'
            });
          }).catch(() => {
            this.$notify.error({
              title: '失败',
              message: '更新失败'
            });
          })
        } else {
          this.$message('请按照要求填写数据！');
          return false;
        }
      });
    },
    handlerEdit(row) {
      if (!row.isDie) {
        this.$notify({
          title: '警告',
          message: '当前任务已被终结！',
          type: 'warning'
        });
        return;
      }
      this.taskForm = row
      this.dialogTaskVisible = true
    },
    handlerSelectionChangeEdit() {
      this.taskForm = this.multipleSelection[0]
      this.dialogTaskVisible = true
    },
    handlerSelectionChangeDeleted() {
      var ids = this.multipleSelection.map(item => item.id);
      batchDeleted({ids: ids}).then(res => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success'
        });
      }).catch(() => {
        this.$notify.error({
          title: '失败',
          message: '删除失败'
        });
      })
    },
    handleDropdownClick(command) {
      //this.$message('click on item ' + JSON.stringify(command));
      if (command.type === 1) {
        triggerJob({id:command.item.id}).then(res => {
          this.$notify({
            title: '成功',
            message: '立即执行一次任务成功',
            type: 'success'
          });
        }).catch(() => {
          this.$notify.error({
            title: '失败',
            message: '立即执行一次任务失败'
          });
        })
      }else
      if (command.type === 2) {
        this.taskForm = command.item
        this.dialogDetailsVisible = true
      }else
      if (command.type === 3) {
        this.$message({
          message: '日志已存储，但暂未开通查看功能 ',
          center: true,
          type: 'success'
        });
      }
    },
    handleTaskDieClick(item) {
      this.$message('click on item ' + JSON.stringify(item));
      abortMission({id: item.id}).then(res => {
        this.getJobs()
      }).catch(() => {
        this.$notify.error({
          title: '失败',
          message: '终止任务失败'
        });
      })
    },
    crontabFill(value) {
      //确定后回传的值
      // this.input = value;
      this.taskForm.cron = value;
      this.dialogCronVisible = false
    },

    //日志方法
    handleLog(){
      this.$router.push({ path: '/sys/scheduledLog' })
    }
  },


}
</script>

<style scoped>
.el-table .warning-row {
  background: #f187ac;
}
</style>
